package com.mindcraft.websocket.controller;


import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.mindcraft.base.model.MindCraftResult;
import com.mindcraft.base.utils.CommonConst;
import com.mindcraft.user.po.User;
import com.mindcraft.websocket.client.UserClient;
import com.mindcraft.websocket.config.ImConfigConst;
import com.mindcraft.websocket.po.ImChatGroup;
import com.mindcraft.websocket.po.ImChatGroupUser;
import com.mindcraft.websocket.po.ImChatUserGroupMessage;
import com.mindcraft.websocket.service.ImChatGroupService;
import com.mindcraft.websocket.service.ImChatGroupUserService;
import com.mindcraft.websocket.service.ImChatUserGroupMessageService;
import com.mindcraft.websocket.utils.LoginCheck;
import com.mindcraft.websocket.utils.MindCraftUtil;
import com.mindcraft.websocket.vo.GroupMessageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 群聊记录 前端控制器
 * </p>
 *
 * @author sara
 * @since 2021-12-02
 */
@RestController
@RequestMapping("/webchat/imChatUserGroupMessage")
@Api(value = "聊天室接口", tags = "群聊记录接口")
public class ImChatUserGroupMessageController {

    @Autowired
    private ImChatUserGroupMessageService imChatUserGroupMessageService;

    @Autowired
    private ImChatGroupUserService imChatGroupUserService;

    @Autowired
    private ImChatGroupService imChatGroupService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserClient userClient;

    /**
     * 获取群消息（只获取前四十条）
     */
    @GetMapping("/listGroupMessage")
    @LoginCheck
    @ApiOperation("获取群消息")
    public MindCraftResult<Page> listGroupMessage(@RequestParam(value = "current", defaultValue = "1") Long current,
                                                  @RequestParam(value = "size", defaultValue = "40") Long size,
                                                  @RequestParam(value = "groupId") Integer groupId) {
        Page<ImChatUserGroupMessage> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);

        Integer userId = MindCraftUtil.getUserId();

        ImChatGroup chatGroup = imChatGroupService.getById(groupId);
        if (chatGroup == null) {
            return MindCraftResult.fail("群组不存在！");
        }

        if (chatGroup.getGroupType().intValue() == ImConfigConst.GROUP_COMMON) {
            LambdaQueryChainWrapper<ImChatGroupUser> groupLambdaQuery = imChatGroupUserService.lambdaQuery();
            groupLambdaQuery.eq(ImChatGroupUser::getGroupId, groupId);
            groupLambdaQuery.eq(ImChatGroupUser::getUserId, userId);
            groupLambdaQuery.in(ImChatGroupUser::getUserStatus, ImConfigConst.GROUP_USER_STATUS_PASS, ImConfigConst.GROUP_USER_STATUS_SILENCE);
            Integer count = groupLambdaQuery.count();
            if (count < 1) {
                return MindCraftResult.fail("未加群！");
            }
        }

        LambdaQueryChainWrapper<ImChatUserGroupMessage> lambdaQuery = imChatUserGroupMessageService.lambdaQuery();
        lambdaQuery.eq(ImChatUserGroupMessage::getGroupId, groupId);
        lambdaQuery.orderByDesc(ImChatUserGroupMessage::getCreateTime);
        Page<ImChatUserGroupMessage> result = lambdaQuery.page(page);
        List<ImChatUserGroupMessage> records = result.getRecords();
        Collections.reverse(records);
        if (CollectionUtils.isEmpty(records)) {
            return MindCraftResult.success(result);
        } else {
            List<GroupMessageVO> collect = records.stream().map(message -> {
                GroupMessageVO groupMessageVO = new GroupMessageVO();
                groupMessageVO.setContent(message.getContent());
                groupMessageVO.setFromId(message.getFromId());
                groupMessageVO.setToId(message.getToId());
                groupMessageVO.setId(message.getId());
                groupMessageVO.setGroupId(message.getGroupId());
                groupMessageVO.setCreateTime(message.getCreateTime());
                Integer messageUserId = message.getFromId();
                User user = this.getUser(messageUserId);
                if (user != null) {
                    groupMessageVO.setUsername(user.getUsername());
                    groupMessageVO.setAvatar(user.getAvatar());
                }
                return groupMessageVO;
            }).collect(Collectors.toList());
            Page<GroupMessageVO> resultVO = new Page<>();
            resultVO.setRecords(collect);
            resultVO.setTotal(result.getTotal());
            resultVO.setCurrent(result.getCurrent());
            resultVO.setSize(result.getSize());
            return MindCraftResult.success(resultVO);
        }
    }

    private User getUser(Integer userId) {
        User user = (User) redisTemplate.opsForValue().get(CommonConst.USER_CACHE + userId.toString());
        if (user != null) {
            return user;
        }
        User u = userClient.getUser(userId);
        if (u != null) {
            redisTemplate.opsForValue().set(CommonConst.USER_CACHE + userId.toString(), u, CommonConst.EXPIRE, TimeUnit.SECONDS);
            return u;
        }
        return null;
    }
}

